from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

# Create your views here.
from terrace.models import RolesModel,ResourceModel,Role_ResourceModel,PageResource,AdminUserModel
from utils.mysql_db import dbs
import json
class RoleHandler(APIView): # 角色表
    def get(self):
        sql = "select * from roles"
        res = dbs.find_all(sql)
        return Response({'msg': '发送成功', 'code': 200,'data':res})

    def post(self):
        data = json.loads(self.request.body)
        name = data["name"]
        sql = "select * from roles where name = '%s'"%name
        res = dbs.findone(sql)
        if res:
            return Response({'msg': '已存在', 'code': 400})
        sql = "insert into roles(name) values ('%s')"%name
        dbs.add(sql)
        dbs.commit()
        return Response({'msg': '发送成功', 'code': 200})

    def put(self):
        pass

    def delete(self):
        pass


class ResourceHandler(APIView): # 角色——资源表 userid 是角色表的id
    def get(self):
        rid = self.get_query_argument("rid")
        sql = "select * from resource where pid != 0"
        res = dbs.find_all(sql)
        data = [{"key":i["id"],"label":i["name"]} for i in res]
        sql1 = "select resourceid from role_resource where userid=%d"%int(rid)
        res = dbs.find_all(sql1)
        lst = []
        for i in res:
            lst.append(i["resourceid"])
        return Response({"code": 200,"data":data,"lst":lst})

    def post(self):
        data = json.loads(self.request.body)
        userid = int(data["userid"])
        resourceid = data["resourceid"]
        print(resourceid)
        sql = "delete from role_resource where role_id=%d"%userid
        dbs.add(sql)
        for i in resourceid:
            sql = "insert into role_resource(role_id,resourceid) values (%d,%d)"%(userid,int(i))
            dbs.add(sql)
        dbs.commit()
        return Response({"code": 200, "msg":"配置资源成功"})


class SetResource(APIView):   # 资源表
    def post(self):
        data = json.loads(self.request.body)
        name = data["name"]
        pid = int(data["pid"])
        url = data["url"]
        sql = "insert into resource(name,pid,url,type) values ('%s',%d,'%s',%d)"%(name,pid,url,1)
        dbs.add(sql)
        dbs.commit()
        return Response({"code": 200, "msg":"添加资源成功"})
    # 获取id!=0的分类   下拉框
    def get(self):
        sql = "select * from resource where pid != 0"
        res = dbs.find_all(sql)
        return Response({"code": 200, "msg":"获取资源成功","data":res})


class getMenu(APIView):  # 获取用户权限
    def get(self,request):
        roleid = request.GET.get('roleid')
        sql = "select re.*,pre.name as pname from role_resource as rr left join resource as re on rr.resourceid=re.id left join resource as pre on pre.id = re.pid where rr.roleid=%d" % int(roleid)
        res = dbs.find_all(sql)
        # 新建list=[],遍历列表res，将父类放入List列表中
        list = []
        idlist = []
        for i in res:
            if i["pid"] not in idlist:
                list.append({"id": i["pid"], "name": i["pname"], "son": []})
                idlist.append(i["pid"])
        # 遍历res,把出子类和父类list进行对比，如果相同放到son,son.append
        for j in res:
            for index, p in enumerate(list):
                if j['pid'] == p['id']:
                    list[index]['son'].append({"id": j['id'], "name": j['name'], 'url': j['url']})
        return Response({"code": 200, 'list': list})

